package com.ygqh.baby.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.redis.RedisDao;

import net.sf.json.JSONObject;

public class YgCacheInterceptor implements HandlerInterceptor {
	@Autowired
	private RedisDao redisDao;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String path = request.getServletPath();
		String mothodName = path.substring(path.lastIndexOf("/") + 1, path.indexOf("."));
		String redisKey = null;
		switch (mothodName) {
		case "findOwnPromotionListNotLogin":

			String productId = request.getParameter("productId");
			redisKey = mothodName + "_" + productId;
			break;

		case "newSearch4Index":
			String start = request.getParameter("start");
			if (Integer.parseInt(start) == 0) {
				redisKey = mothodName;
			}
			break;
		case "similarityPublish":
			String productId1 = request.getParameter("productId");
			String groupId = request.getParameter("groupId");
			redisKey = mothodName + "_" + productId1 + "_" + groupId;
			break;
		case "getSearchKeywords":
			redisKey = mothodName;
			break;
		case "getProductRecommend":
			String groupIdr = request.getParameter("groupId");
			redisKey = mothodName + "_" + groupIdr;
			break;
		}
		if (!StringUtil.isBlank(redisKey)) {

			try {
				String result = redisDao.get(redisKey);
				if (StringUtil.isNotBlank(result)) {
					response.setHeader("Content-type", "text/html;charset=UTF-8");
					String callback = request.getParameter("callback");
					response.getWriter().print(callback + "(" + JSONObject.fromObject(Message.success("", result)).toString() + ")");
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return true;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// TODO Auto-generated method stub
	}

}
